import { lazy, Suspense, useEffect } from 'react'
import { useRoutes, BrowserRouter, useLocation, useNavigate } from 'react-router-dom'

const Login = lazy(() => import('../pages/login/Login'))
const Blog = lazy(() => import('../pages/blog/Blog'))
const Index = lazy(() => import('../pages/index/Index'))
const NotFound = lazy(() => import('../pages/notFound/notFount'))
const Me = lazy(() => import('../pages/Me/Me'))
const BlogDetail = lazy(() => import('../pages/blog/BlogDetail'))
const Message = lazy(() => import('../pages/message/Message'))
const Chat = lazy(() => import('../pages/chat/chat'))

const routerConfig = [
  {
    path: '/login',
    element: <Login></Login>
  },
  {
    path: '/',
    element: <Index></Index>,
    children: [
      {
        path: '/blog',
        element: <Blog></Blog>
      },
      {
        path: '/me',
        element: <Me></Me>
      },
      {
        path: '/login',
        element: <Login></Login>
      },
      {
        path: '/message',
        element: <Message></Message>
      },
      {
        path: '/detail/:id',
        element: <BlogDetail></BlogDetail>
      },
      {
        path: '/chat',
        element: <Chat></Chat>
      }
    ]
  },
  {
    path: '*',
    element: <NotFound></NotFound>
  }
]
const ProtectRouter = () => {
  routerConfig.forEach(item => {
    item.element = <Suspense fallback={<>123</>}>{item.element}</Suspense>
  })

  const Routers = () => useRoutes(routerConfig)
  const location = useLocation()
  const navigation = useNavigate()
  useEffect(() => {
    location.pathname === '/' && navigation('/blog')
  }, [location.pathname])
  return <Routers></Routers>
}
const Router = () => {
  return (
    <BrowserRouter>
      <ProtectRouter></ProtectRouter>
    </BrowserRouter>
  )
}

export default Router
